package com.landis.temple.mobile;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;


/**
 * Class holds all twitter login and use functions
 * 
 * @author John Landis 
 * @author Anton Kronaj
 *
 */
public class TwitterBackend
{
	
	private static final String TAG = "TwitterBackend";
	
	private static final String TOKEN_REP = "token";
    private static final String TOKEN_SECRET_REP = "tokenSecret";
    private static final String VERIFIER_REP = "verifier";
    private static final String IS_LOGGED_IN_REP = "isLoggedOut";
    
    private static final String CONSUMER_KEY = "8Xv8yYZPyDOiUi1A43oCQ";
    private static final String CONSUMER_SECRET = "wou4R6qlq3L5CuPkF9O9WetOx1sclwNm1QCNuyXylkk";
    
    private static final String CALLBACK_URL = "twitterstory://twit";
    
    private static CommonsHttpOAuthProvider provider = new CommonsHttpOAuthProvider( "http://twitter.com/oauth/request_token", 
                                                                                     "http://twitter.com/oauth/access_token" , 
                                                                                     "http://twitter.com/oauth/authorize"    );
    
	private static CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    private static Twitter twitter;
    private static SharedPreferences prefs;
    
    public static boolean isLoggedIn = false;
    
    
    /**
     *  Sets up TwitterBackend for use
     * 
     * @param activity - needed for access to the preferences
     */
    public static void init(Activity activity)
    {
    	prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    	isLoggedIn = prefs.getBoolean(IS_LOGGED_IN_REP, false);
    	Log.e(TAG, "in init(): isLoggedIn = " + isLoggedIn);
    }
    
    /**
     * Starts new browser activity to do twitter login
     * Results will be dealt with in the newIntent()
     * 
     * @param activity - used to make toasts and start another activity
     */
    public static void askOAuth(Activity activity) 
    {
        Log.d( TAG , "in askOAuth" );
		try 
		{			
			Log.e(TAG, "in askOAuth(): isLoggedIn = " + isLoggedIn);
			String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
			Toast.makeText( activity , "Please authorize this app!", Toast.LENGTH_LONG).show();
			activity.startActivity(new Intent(Intent.ACTION_VIEW , Uri.parse(authUrl)));
		} 
		catch (Exception e) 
		{
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
			Toast.makeText( activity , e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

    // must be placed in on NewIntent() of the activity using it in
	public static void process(Intent intent, Activity a) 
	{
        Log.d( TAG , "in process" );
        Log.e(TAG, "in process(): isLoggedIn = " + isLoggedIn);
		Uri uri = intent.getData();
		
		if ( uri != null && uri.toString().startsWith(CALLBACK_URL)) 
		{
			String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
			try {
				
				// this will populate token and token_secret in consumer
				provider.retrieveAccessToken(consumer, verifier);
				
				String token = consumer.getToken();
				String tokenSecret = consumer.getTokenSecret();
				// Store token in prefs
				isLoggedIn = true;
				prefs.edit().putString( TOKEN_REP        , token       )
		        			.putString( TOKEN_SECRET_REP , tokenSecret )
		        			.putString( VERIFIER_REP     , verifier    )
		        			.putBoolean(IS_LOGGED_IN_REP	 , true).commit();
		        
		        logIn(token, tokenSecret);
		        				
				Toast.makeText(a, twitter.getScreenName(), Toast.LENGTH_LONG).show();
			} 
			catch (Exception e) 
			{
				Log.e(TAG, "exception in on Process(): " + e.getMessage());
				e.printStackTrace();
				Toast.makeText(a, e.getMessage(), Toast.LENGTH_LONG).show();
			}
		}
		
	}
	
	public static void testLogin(Activity a)
	    {
			Log.e(TAG, "in testLogin(): isLoggedIn = " + isLoggedIn);
	        String token = getToken();
	        String tokenSecret = getTokenSecret();
	        String verifier = getVerifier();
//	        isLoggedIn = prefs.getBoolean(IS_LOGGED_IN_REP, false);
	        
	        Log.e(TAG, "in testLogin(): isLoggedIn = " + isLoggedIn);
	        Log.d( TAG, "Token in testLogin: " + token );
	        Log.d( TAG, "SecretToken in testLogin: " + tokenSecret );
	        Log.d( TAG, "Verifier in testLogin: " + verifier );
	        
	        if ( isLoggedIn && token != null && tokenSecret != null && verifier != null) 
	        {
	            logIn(token, tokenSecret);
	          
	            TwitterLibrary.userName = getUsername();
	            Log.d( TAG , "user in testLogin(): " + TwitterLibrary.userName);
	            Toast.makeText(a,TwitterLibrary.userName, Toast.LENGTH_LONG).show();                
	            TwitterLibrary.setAuthor( TwitterLibrary.userName);
	        }
	        else
	        {
	        	Toast.makeText(a,"Please log in to authorize this app!", Toast.LENGTH_LONG).show();  //askOAuth(a);
	        }
	    }
	
	public static void logIn(String token, String tokenSecret)
	{
		AccessToken a = new AccessToken(token, tokenSecret);
		twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
		twitter.setOAuthAccessToken(a);
		
	}
	
	public static void logOut()
	{
		prefs.edit().remove(TOKEN_REP).remove(TOKEN_SECRET_REP).remove(VERIFIER_REP).commit();
        prefs.edit().putBoolean(IS_LOGGED_IN_REP, false).commit();
        isLoggedIn = false;
	}
	
	public static String getUsername()
	{
		if(isLoggedIn)
		{
			try 
			{
				return twitter.getScreenName();
			} 
			catch (IllegalStateException e) 
			{
				e.printStackTrace();
			} 
			catch (TwitterException e) 
			{
				e.printStackTrace();
			}
		}
		return "You are logged out";
	}
	
	public static String getToken()
	{
		return prefs.getString(TOKEN_REP, null);
	}
	
	public static String getTokenSecret()
	{
		return prefs.getString(TOKEN_SECRET_REP, null);
	}
	
	public static String getVerifier()
	{
		return prefs.getString(VERIFIER_REP, null);
	}
	
	public static void tweet(String tweet, Activity a)
	{
		// send the tweet
		try 
		{
			twitter.updateStatus(tweet);
		} 
		catch (TwitterException e) 
		{
			e.printStackTrace();
		}
    }
}
